<template>
  <div>
    <!-- 添加签证产品 -->
    <el-button
        class="addVisaProduct"
        type="primary"
        round
        @click="addVisaProduct"
        style="background-color: #803f7d; border-color: #000000;">
      <i class="el-icon-plus" style="margin-right: 3px;"></i>添加签证产品
    </el-button>

    <!-- 搜索框 -->
    <el-input
        v-model="searchKeyword"
        placeholder="输入签证产品名称搜索"
        clearable
        style="width: 300px; float: right; margin-bottom: 20px;"
        @clear="fetchVisaProduct"
        @keyup.enter.native="fetchVisaProduct"
    >
      <el-button slot="append" icon="el-icon-search" @click="fetchVisaProduct" />
    </el-input>

    <!--签证产品列表-->
    <el-table
        :data="visaProductData"
        style="width: 100%"
        border
        :cell-style="{ borderRight: 'none' }"
        :header-cell-style="{ borderRight: 'none' }"
    >
      <el-table-column fixed prop="name" label="产品名称"></el-table-column>
      <el-table-column prop="countryName" label="国家"></el-table-column>
      <el-table-column prop="continent" label="所属大陆"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="transactTime" label="办理时长"></el-table-column>
      <el-table-column prop="maxStay" label="最长停留"></el-table-column>
      <el-table-column prop="entryNumber" label="入境次数">
        <template slot-scope="scope">
          {{ formatEntryNumber(scope.row.entryNumber) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="添加时间"></el-table-column>
      <el-table-column prop="isShow" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
              v-model="row.isShow"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              active-color="#803f7d"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button @click="handleEdit(row)" type="primary"  plain size="small">编辑</el-button>
          <el-button @click="handleDelete(row)" type="danger" plain size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import service from "@/utils/request";

export default {
  data() {
    return {
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 搜索相关
      searchKeyword: '',

      loading: false,

      visaProductData: [],
    };
  },
  mounted() {
    this.fetchVisaProduct();
  },
  methods: {
    // 修改添加按钮的方法
    async addVisaProduct() {
      const button = document.querySelector('.addVisaProduct');
      button.disabled = true;

      this.$router
          .push({ 
            name: 'addVisaProduct',
            params: { mode: 'add' }  // 添加模式标识
          })
          .catch(err => {
            if (err.name !== 'NavigationDuplicated') {
              console.error(err);
            }
          })
          .finally(() => {
            setTimeout(() => {
              button.disabled = false;
            }, 500);
          });
    },

    formatEntryNumber(value) {
      const entryNumberMap = {
        '-1': '不限',
        '1': '1次',
        '99': '多次'
      };
      return entryNumberMap[value] || value;
    },
    // 修改编辑按钮的方法
    handleEdit(row) {
      this.$router.push({
        name: 'addVisaProduct',
        params: { 
          mode: 'edit',  // 编辑模式标识
          id: row.id 
        }
      });
    },
    async fetchVisaProduct() {
      this.loading = true;
      try {
        const res = await service.get('/admin/visaProduct/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.searchKeyword,
            _: Date.now()
          },
          headers: {'Cache-Control': 'no-cache'}
        });
        console.log('fetchVisaProduct response:', res.data); // 添加调试
        // 兼容不同响应结构
        const records = res.data.data?.records || res.data.records || [];
        const total = res.data.data?.total || res.data.total || 0;
        this.visaProductData = records;
        this.total = total;

      } catch (error) {
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchVisaProduct();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchVisaProduct();
    },
    async handleDelete(row) {
      this.$confirm('确定要删除该签证产品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteVisaProduct(row.id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async deleteVisaProduct(id) {
      try {
        const res = await service.delete(`/admin/visaProduct/${id}`);

        if (res.code === 1) {
          this.$message.success('删除成功');
          await this.fetchVisaProduct(); // 刷新列表
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      } catch (error) {
        this.$message.error('删除出错');
        console.error(error);
      }
    },
    async handleStatusChange(row) {
      const originalStatus = row.isShow;
      try {
        const res = await service.post(`/admin/visaProduct/status/${row.isShow}`, null, {
          params: { id: row.id }
        });

        if (res.code === 1) {
          this.$message.success('状态更新成功');
          // 在状态更新成功后，手动更新 tableData
          const index = this.visaProductData.findIndex(item => item.id === row.id);
          if (index !== -1) {
            // 使用 $set 确保 Vue 能够检测到数组的变化
            this.$set(this.visaProductData, index, { ...this.visaProductData[index], isShow: row.isShow });
          }
        } else {
          throw new Error(res.msg || '更新失败');
        }
      } catch (error) {
        this.$message.error(error.message || '更新失败');
        row.isShow = originalStatus;
      }
    },
  },
};
</script>

<style scoped>
.addVisaProduct {
  margin-bottom: 20px;
  float: left;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>